package cn.school.demo.ui.modify_password

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import cn.school.demo.MyApplication
import cn.school.demo.pojo.Result
import cn.school.demo.repository.ForgetPasswordRepository
import cn.school.demo.util.StringUtil

class ModifyPwdViewModel : ViewModel() {
    private lateinit var _result: LiveData<Result>
    val result: LiveData<Result> get() = _result

    private val _isBrowse = MutableLiveData<Boolean>()
    val isBrowse: LiveData<Boolean> get() = _isBrowse

    private val _pwd = MutableLiveData<String>()
    val pwd: LiveData<String> get() = _pwd

    private val _isGone = MutableLiveData<Int>()
    val isGone: LiveData<Int> get() = _isGone

    private val _newPwd = MutableLiveData<String>()
    val newPwd: LiveData<String> get() = _newPwd

    private val _newRePwd = MutableLiveData<String>()
    val newRePwd: LiveData<String> get() = _newRePwd

    init {
        _isBrowse.value = false
        _pwd.value = ""
        _isGone.value = 0
        _newPwd.value = ""
        _newRePwd.value = ""
    }

    fun changeBrowse() {
        _isBrowse.value = !_isBrowse.value!!
    }

    fun changeEdit(text: String) {
        _pwd.value = text
    }

    fun pwdIsTrue(): Boolean {
        return _pwd.value == MyApplication.user!!.password
    }

    fun setIsGone(number: Int) {
        _isGone.value = number
    }

    fun setNewPwd(pwd: String) {
        _newPwd.value = pwd
    }

    fun setNewRePwd(pwd: String) {
        _newRePwd.value = pwd
    }

    fun getResult() {
        val params = mapOf<String, Any>(
            "sfNumber" to MyApplication.user!!.sfNumber,
            "password" to _newPwd.value.toString()
        )
        _result = ForgetPasswordRepository().resetPassword(params)
    }

    fun isLegal() = when {
        _newPwd.value.toString().isEmpty() -> "密码不能为空！"
        _newRePwd.value.toString().isEmpty() -> "重复密码不能为空！"
        !StringUtil.isPassword(_newPwd.value.toString()) -> "密码输入不合法！"
        !StringUtil.isPassword(_newRePwd.value.toString()) -> "输入密码输入不合法！"
        _newPwd.value.toString() != _newRePwd.value.toString() -> "密码输入不一致！"
        else -> null
    }
}